//
//  ListeJeuxController.m
//  xKey Interface
//
//  Created by Guillaume SOURDRILLE on 19/02/12.
//  Copyright (c) 2012 Edenyorke. All rights reserved.
//

#import "ListeJeuxController.h"
#import "URLConnection.h"
#import "DataXmlParser.h"
#import "GameXmlParser.h"
#import "MessageUtils.h"
#import "Data.h"

@implementation ListeJeuxController
@synthesize request, urlConnection,detailJeuViewController,messageUtils,alertLoadingData,progressView;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initConnection];
   
    alertLoadingData = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"alert.loading.content", @"") message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    
    [self initData];
    

    
   }

- (void)viewDidUnload
{
    [super viewDidUnload];
    request = nil;
    urlConnection = nil;
    messageUtils = nil;
    detailJeuViewController = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle: NSLocalizedString(@"button.back", @"") style:UIBarButtonItemStylePlain target:self action:@selector(closeView)];
    self.navigationItem.leftBarButtonItem = backButton;
    
    UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc] initWithTitle: NSLocalizedString(@"button.reload", @"") style:UIBarButtonItemStylePlain target:self action:@selector(refreshData)];
    self.navigationItem.rightBarButtonItem = refreshButton;
    
     
}


- (void) closeView {
    [self dismissModalViewControllerAnimated:YES];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *MyIdentifier = @"MyIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:MyIdentifier];
    }
    int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
    
    cell.textLabel.text = [[donnees objectAtIndex: storyIndex] objectForKey: @"TITLE"];
    
    if (([banner isEqualToString:@"ON"])&&([[donnees objectAtIndex: storyIndex] objectForKey: @"BANNER"] != nil)){
           [[cell imageView] setImage:[[donnees objectAtIndex: storyIndex] objectForKey: @"BANNER"]];
    }else{
        [[cell imageView] setImage:[[donnees objectAtIndex: storyIndex] objectForKey: @"COVER"]];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 75;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    idJeu = [[donnees objectAtIndex: indexPath.row] objectForKey: @"ID"];
    nomJeux = [[donnees objectAtIndex: indexPath.row] objectForKey: @"TITLE"];
    descriptionJeu = [[donnees objectAtIndex: indexPath.row] objectForKey: @"DESCRIPTION"];
    imageJeu = [[donnees objectAtIndex: indexPath.row] objectForKey: @"COVER"];

    
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        detailJeuViewController = [[DetailJeuxView alloc] initWithNibName:@"DetailJeuxViewIpad" bundle:nil];
    }
    else {
        if ([[UIScreen mainScreen] bounds].size.height == 568) {
            detailJeuViewController = [[DetailJeuxView alloc] initWithNibName:@"DetailJeuxView4retina" bundle:nil];
            //this is iphone 5 xib
        } else {
            detailJeuViewController = [[DetailJeuxView alloc] initWithNibName:@"DetailJeuxView" bundle:nil];
        }
        
    }
    
    [detailJeuViewController setParam:nomJeux :idJeu :imageJeu :descriptionJeu];
    detailJeuViewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentModalViewController:detailJeuViewController animated:YES];
    
}




- (void)initConnection {
    
    urlConnection = [[URLConnection alloc] initWithIp];
}

- (void)initData {
    messageUtils = [[MessageUtils alloc]init];
    banner = [messageUtils getValue:@"banner"];
    
    Data *data = [Data sharedInstance];
    if ([data getDonnees] == nil){
        [self showAlertLoadingData];
        [self performSelectorInBackground:@selector(getData) withObject:nil ];
        [self.tableView reloadData];
    }else{
        donnees = [data getDonnees];
        [self.tableView reloadData];
        //  [self hideAlertLoadingData];
    }

}

- (void)refreshData {
    [self showAlertLoadingData];
    [self performSelectorInBackground:@selector(getData) withObject:nil ];
    
}

- (void)getData {
    
    NSURL *url = [urlConnection getURLForXml];
    DataXmlParser *xmlParser = [[DataXmlParser alloc]init];
    GameXmlParser *gameParser = [[GameXmlParser alloc]init];
    
    
    donnees = [[NSMutableArray alloc] init];
    donnees = [xmlParser parseXmlFromUrl:url];
    if ([donnees count] != 0){
        for(int index = 0; index < [donnees count]; index++){
            float count = [donnees count];
            NSNumber *progress = [NSNumber numberWithFloat:(index/count)];
            NSDictionary *array = [donnees objectAtIndex:index];
            [self performSelectorOnMainThread: @selector(makeMyProgressBarMoving:) withObject: progress waitUntilDone: NO];
            array = [gameParser completeXml:array];
            if ([array objectForKey: @"COVER"] == nil){
                UIImage *image = [gameParser getCoverFromId:[array objectForKey: @"ID"]];
                if (image  != nil){
                    [array setValue:image forKey:@"COVER"];
                }

            }

                        
            
            NSString* title =  [NSString stringWithFormat:@"%i/%i\n%@", (index+1),[donnees count], [array objectForKey:@"TITLE"]];
            [self performSelectorOnMainThread: @selector(changeProgressBarTitle:) withObject: title waitUntilDone: NO];
            [donnees replaceObjectAtIndex:index withObject:array];
         }
        
        
        
        //Sorting games
        NSSortDescriptor *gameSorter = [[NSSortDescriptor alloc] initWithKey:@"TITLE" ascending:YES];
        [donnees sortUsingDescriptors :[NSArray arrayWithObject:gameSorter]];
        
        Data *data = [Data sharedInstance];
        [data setDonnees:donnees];
    }else{
        [self hideAlertLoadingData];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"popup.error.title", @"")
                                                        message:NSLocalizedString(@"popup.error.content", @"")
                                                       delegate:nil
                                              cancelButtonTitle:@"OK" 
                                              otherButtonTitles:nil];
        [alert show];
    }
    xmlParser = nil;
    gameParser = nil;
    [self.tableView reloadData];
    [self hideAlertLoadingData];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [donnees count];
}

- (void)showAlertLoadingData{
   
    [alertLoadingData show];
    progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(30.0f, 80.0f, 225.0f, 90.0f)];
    [alertLoadingData addSubview:progressView];
    [progressView setProgressViewStyle: UIProgressViewStyleBar];

[alertLoadingData show];

  }

- (void)hideAlertLoadingData{
        [alertLoadingData dismissWithClickedButtonIndex:0 animated:YES];
   }

-(void)makeMyProgressBarMoving: (NSNumber*) progress {
    progressView.progress = [progress floatValue];
}


-(void)changeProgressBarTitle: (NSString*) title {
    [alertLoadingData setTitle:title];
}

@end
